#!/bin/sh
# -* coding: UTF-8 *-

luf_kernel_name="2.6.25-gentoo-r7-via-c7"
luf_kernel_archive="/misc/gentoo/kernels/kernel-image-${luf_kernel_name}.tar.bz2"
luf_stagedir="/misc/gentoo/stages/i686/liveusb"

luf_workdir="/var/tmp/liveusb"
luf_device="/dev/sda"
#luf_device="/dev/sdb"

luf_boot_size=                # Boot partition in blocks (1 block 1024 bytes)
luf_boot_label="usb-boot"     #

luf_data_use="no"
luf_data_label="usb-data"

depend() {
    if [ -z "${squashfs_path}" -o ! -x "${squashfs_path}" ] ; then
        eerror "squashfs program not found"
        return 8
    fi

    if [ -z "${luf_device}" -o ! -b "${luf_device}" ] ; then
        eerror "invalid block device"
        return 8
    fi
    return 0
}

init_workdir() {
    local retval

    luf_init_workdir "$@" ; retval=$?
    [[ ${retval} -ne 0 ]] && return ${retval}
    return ${retval}
}

copy_stage() {
    local retval

    einfo "!!! user copy function"

    luf_copy_stage "$@" ; retval=$?
    [[ ${retval} -ne 0 ]] && return ${retval}

    rm -fr "${luf_workdir}"/source/misc/*
    rm -fr "${luf_workdir}"/source/var/cache/edb/*

    #
    # Script make some actions in live filesystem
    #
    rm -f "${luf_workdir}"/source/etc/init.d/pg_autovacuum

    (
        echo ""
        echo "# !!! Disable update of /etc/inittab file"
        echo "livecd_fix_inittab() {"
        echo "    return 0"
        echo "}"
    ) >> "${luf_workdir}"/source/sbin/livecd-functions.sh

    (
        echo "# /etc/conf.d/local.start"
        echo ""
        echo "# This is a good place to load any misc programs"
        echo "# on startup (use &>/dev/null to hide output)"
        echo ""
    ) > "${luf_workdir}"/source/etc/conf.d/local.start

    ebegin  "Creating /etc/fstab and cleaning /etc/mtab"
    mkdir -p "${luf_workdir}"/source/etc

    (
        echo "LABEL=${luf_boot_label} /               ext2            rw,defaults     0 1"
        echo "none           /proc           proc            defaults        0 0"
        echo "none           /dev/shm        tmpfs           defaults        0 0"
        echo "#none          /dev/pts        devpts          defaults        0 0"
        echo "tmpfs          /tmp            tmpfs           defaults,nosuid,mode=1777   0 0"
    ) > "${luf_workdir}"/source/etc/fstab
    rm -f "${luf_workdir}"/source/etc/mtab

    if [ "${luf_data_use}" = "yes" ] ; then
        einfo "Create read/write data mountpoint"
        echo "LABEL=${luf_data_label}  /mnt/.usbdata   ext2            defaults        0 0" \
            >> "${luf_workdir}"/source/etc/fstab
        mkdir -p "${luf_workdir}"/source/mnt/.usbdata
    fi

    #
    mount_portages ; retval=$?
    [[ ${retval} -ne 0 ]] && return ${retval}

    do_in_chroot "in_chroot" "$@" ; retval=$?
    [[ ${retval} -ne 0 ]] && return ${retval}

    umount_portages ; retval=$?
    [[ ${retval} -ne 0 ]] && return ${retval}

    # Set Default X11 Session
    tar -C "${luf_workdir}"/source/home/local \
        -xf ${luf_config_dir}/local-xfce4.tar

    ebegin "Installing GRUB configuration file"
    rm -f "${luf_workdir}"/source/boot/grub/menu.lst
    (
        echo "default 0"
        echo "timeout 5"
        echo "#splashimage=(hd0,0)/boot/grub/splash.xpm.gz"
        echo ""
        echo "title=Boot LiveUSB"
        echo "root (hd0,0)"
        echo "kernel (hd0,0)/boot/kernel-genkernel-x86-${luf_kernel_name} root=/dev/ram0 init=/linuxrc real_root=LABEL=${luf_boot_label} udev nodevfs"
        echo "initrd (hd0,0)/boot/initramfs-genkernel-x86-${luf_kernel_name}"
        echo ""
        echo "title=Boot LiveUSB (SATA+IDE)"
        echo "root (hd0,0)"
        echo "kernel (hd0,0)/boot/kernel-genkernel-x86-${luf_kernel_name} root=/dev/ram0 init=/linuxrc real_root=LABEL=${luf_boot_label} udev nodevfs doide"
        echo "initrd (hd0,0)/boot/initramfs-genkernel-x86-${luf_kernel_name}"
        echo ""
        echo "title=Boot LiveUSB (No SATA)"
        echo "root (hd0,0)"
        echo "kernel (hd0,0)/boot/kernel-genkernel-x86-${luf_kernel_name} root=/dev/ram0 init=/linuxrc real_root=LABEL=${luf_boot_label} udev nodevfs nosata doide"
        echo "initrd (hd0,0)/boot/initramfs-genkernel-x86-${luf_kernel_name}"
    ) > "${luf_workdir}"/source/boot/grub/menu.lst
    eend $?

    return ${retval}
}

install_image() {
    ebegin "!! user install function"

    ### Remove source dir from images
    luf_images=

    ### Move /opt and /usr to squashfs image
    image="extra"
    ebegin "Spliting stage to ${image} part"
    create_image "${image}" "/" "auto"
    move_to_image "${image}" /usr
    move_to_image "${image}" /opt
    move_to_image "${image}" /var/db/pkg
    eend $?

    ### Remove portage metadata cache
    rm -fr "${luf_workdir}"/source/var/cache/edb/*

    ### Correct /etc/fstab entries for squashfs images
    sed -i -e "s|^/mnt/cdrom/image.|/image.|" "${luf_workdir}"/source/etc/fstab

    ### Install root into target directory
    retval1=255
    ebegin "Copy boot content"
    do_rsync --delete --partial --archive "${luf_workdir}"/source/* "${luf_workdir}"/target/ ; retval1=$?
    [[ ${retval} -ne 0 ]] && return ${retval}
    eend ${retval}

    ### Build squash
    ebegin "Build suashfs images"
    luf_build_squash_images "$@" ; retval=$?
    eend ${retval}
    [[ ${retval} -ne 0 ]] && return ${retval}
    return 0
}

install_media() {
    ### Make out USB-flash
    ebegin "Make out USB-flash drive ${luf_device}"
    eindent 1
    make_out_flash "$@" ; retval=$?
    eoutdent 1
    eend ${retval}
    [[ ${retval} -ne 0 ]] && return ${retval}

    ### Remove /cdupdate.sh
    rm -f "${luf_workdir}"/target/cdupdate.sh

    ### Copy files to USB-flash
    ebegin "Copy files to USB-flash ${luf_device}"
    eindent 1
    copy_boot_to_usbflash "$@" ; retval=$?
    if [ ${retval} -eq 0 ] ; then
        copy_data_to_usbflash "$@" ; retval=$?
    fi
    eoutdent 1
    eend ${retval}
    [[ ${retval} -ne 0 ]] && return ${retval}


    ### Install GRUB
    ebegin "Install GRUB to USB-flash ${luf_device}"
    eindent 1
    install_grub "$@" ; retval=$?
    eoutdent 1
    eend ${retval}
    return 0
}

in_chroot() {
    eindent 1
    einfo "Updating chroot"

    rc-update add syslog-ng default
    rc-update add xdm default
    rc-update delete netmount
    rc-update delete modules

    # Add user
    userdel -r local
    useradd -m -G wheel,audio,plugdev local

    # Change users passwords
    echo "root:root" | chpasswd
    echo "local:local" | chpasswd

    depmod -a "${luf_kernel_name}"
    update-modules --force

    update-env

    eoutdent 1
    return 0
}

mount_portages() {
    ebegin "Mount portage tree"
    mount --bind /usr/portage "${luf_workdir}"/source/usr/portage
    eend $?

    if [ -d "${luf_workdir}"/source/usr/portage/packages ] ; then
        ebegin "Mount binary packages dir"
        mount --bind /misc/gentoo/packages/i686/desktop "${luf_workdir}"/source/usr/portage/packages
        eend $?
    fi

    if [ -d "${luf_workdir}"/source/usr/portage/distfiles ] ; then
        ebegin "Mount source files dir"
        mount --bind /misc/gentoo/distfiles "${luf_workdir}"/source/usr/portage/distfiles
        eend $?
    fi
}

umount_portages() {
    if [ -d "${luf_workdir}"/source/usr/portage/distfiles ] ; then
        if is_mount "${luf_workdir}"/source/usr/portage/distfiles ; then
            ebegin "Unmount source files dir"
            umount "${luf_workdir}"/source/usr/portage/distfiles
            eend $?
        fi
    fi

    if [ -d "${luf_workdir}"/source/usr/portage/packages ] ; then
        if is_mount "${luf_workdir}"/source/usr/portage/packages ; then
            ebegin "Unmount binary packages dir"
            umount "${luf_workdir}"/source/usr/portage/packages
            eend $?
        fi
    fi

    if is_mount "${luf_workdir}"/source/usr/portage ; then
        ebegin "Unmount portage tree dir"
        umount "${luf_workdir}"/source/usr/portage
        eend $?
    fi
}

copy_boot_to_usbflash() {
    local retval
    local retval1

    mkdir -p "${luf_workdir}"/mountpoint ; retval=$?
    if [ ${retval} -ne 0 ] ; then
        return ${retval}
    fi

    retval1=255
    ebegin "Copy boot content"
    mount "${luf_device}"1 "${luf_workdir}"/mountpoint ; retval=$?
    if [ ${retval} -eq 0 ] ; then
        do_rsync --delete --partial --archive "${luf_workdir}"/target/* "${luf_workdir}"/mountpoint ; retval1=$?
        umount "${luf_workdir}"/mountpoint ; retval=$?
    fi

    [[ ${retval1} -ne 0 ]] && retval=${retval1}
    eend ${retval}

    rm -r "${luf_workdir}"/mountpoint
    return ${retval}
}

copy_data_to_usbflash() {
    local retval
    local retval1

    [ "${luf_data_use}" = "yes" ] || return 0

    mkdir -p "${luf_workdir}"/mountpoint ; retval=$?
    if [ ${retval} -ne 0 ] ; then
        return ${retval}
    fi

    retval1=255
    ebegin "Copy data content"
    mount "${luf_device}"2 "${luf_workdir}"/mountpoint ; retval=$?
    if [ ${retval} -eq 0 ] ; then
        do_rsync --delete --partial --archive "${luf_workdir}"/usbdata/ "${luf_workdir}"/mountpoint ; retval1=$?
        umount "${luf_workdir}"/mountpoint ; retval=$?
    fi

    [[ ${retval1} -ne 0 ]] && retval=${retval1}
    eend ${retval}

    rm -r "${luf_workdir}"/mountpoint
    return ${retval}
}
